package Dinner;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.example.storage.Fooditem;
import com.example.storage.Foodmanager;
import com.example.storage.MainActivity;
import com.example.storage.Mealdatabase;
import com.example.storage.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import Breakfast.Breakfast;
import Breakfast.BreakfastAdapter;
import Lunch.Lunch;
import mealhistory.MealHistory;
import mealhistory.Mealitem;

public class Dinner extends AppCompatActivity {

    private static final int REQUEST_CODE2 = 1002;
    private RecyclerView recyclerView;
    private DinnerAdapter adapter;
    private Mealdatabase mealdatabase;
    private BottomNavigationView bottomNavigationView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        overridePendingTransition(0,0);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dinner);
        mealdatabase = new Mealdatabase(this, "MEALSTORE.db", null, 3);

        show_navigate();
        show_view();

        ImageButton button_dinner=(ImageButton) findViewById(R.id.button_add_dinner);
        button_dinner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(MainActivity.this,"You clicked Button 1",Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(Dinner.this, Foodmanager.class);
                startActivityForResult(intent,REQUEST_CODE2);
            }
        });

    }

    @Override
    protected void onResume() {
        overridePendingTransition(0,0);
        super.onResume();
        show_navigate();
        show_view();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE2 && resultCode == RESULT_OK) {
            add_data(data,"晚餐");
        }

    }

    public void add_data(Intent data,String Type){
        Fooditem fooditem = (Fooditem) data.getSerializableExtra("food_item");
        // 现在使用 fooditem 对象进行操作
        if (fooditem != null) {
            // 创建对话框
            AlertDialog.Builder builder = new AlertDialog.Builder(Dinner.this);
            builder.setTitle(fooditem.getFoodname());
            builder.setMessage(fooditem.getCalories()+ "/" + fooditem.getUnit()+"克\n食物数量/克(请输入整数):");
            final EditText input = new EditText(Dinner.this);
            input.setInputType(InputType.TYPE_CLASS_NUMBER);
            builder.setView(input);

            // 设置对话框按钮
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // 获取用户输入的食物数量
                    String Squantity = input.getText().toString();
                    try {
                        // 尝试将字符串转换为整数
                        int quantity = Integer.parseInt(Squantity);

                        // 这里你可以使用转换后的整数 quantity 进行其他操作
                        //Toast.makeText(MainActivity.this, "您输入的食物数量是：" + quantity, Toast.LENGTH_SHORT).show();

                        double cal=(double)quantity*fooditem.getCalories()/Integer.parseInt(fooditem.getUnit());

                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        String currentDate = sdf.format(new Date());


                        SQLiteDatabase db = mealdatabase.getWritableDatabase();
                        ContentValues values=new ContentValues();
                        //组装数据
                        values.put("date", currentDate);
                        values.put("weight",quantity);
                        values.put("type",Type);
                        values.put("food",fooditem.getFoodname());
                        values.put("consumption",cal);
                        db.insert("meal",null,values);

                        values.clear();

                        mealdatabase=new Mealdatabase(Dinner.this,"MEALSTORE.db",null,3);
                        show_view();
                    } catch (NumberFormatException e) {
                        // 如果无法转换为整数，则显示错误提示
                        Toast.makeText(Dinner.this, "请输入有效的数量", Toast.LENGTH_SHORT).show();//不显示？？
                    }
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            // 显示对话框
            builder.show();
        } else {
            Toast.makeText(Dinner.this, "未能获取食物信息", Toast.LENGTH_SHORT).show();
        }

    }

    private void show_view(){
        recyclerView = findViewById(R.id.recyclerViewDinner);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 假设有一个方法来获取当天早餐的数据
        List<Mealitem> dinnerItems = getTodayDinnerItems(this);
        adapter = new DinnerAdapter(this, dinnerItems);
        recyclerView.setAdapter(adapter);
    }

    private void show_navigate(){
        bottomNavigationView = findViewById(R.id.navigation);
        bottomNavigationView.setSelectedItemId(R.id.nav_dinner);

        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            int id = item.getItemId();
            if (id == R.id.nav_main) {
                startActivity(new Intent(this, MainActivity.class));
                return true;
            } else if (id == R.id.nav_breakfast) {
                startActivity(new Intent(this, Breakfast.class));
                return true;
            } else if (id == R.id.nav_lunch) {
                startActivity(new Intent(this, Lunch.class));
                return true;
            } else if (id == R.id.nav_dinner) {
                return true;
            } else if (id == R.id.nav_history) {
                startActivity(new Intent(this, MealHistory.class));
                return true;
            }
            return false;
        });
    }

    public static List<Mealitem> getTodayDinnerItems(Context context) {
        List<Mealitem> dinnerItems = new ArrayList<>();
        Mealdatabase mealhelper=new Mealdatabase(context, "MEALSTORE.db", null, 3);
        Cursor cursor = mealhelper.getdinnerData();  // 获取当天晚餐数据的游标

        if (cursor != null) {
            try {
                int idIndex = cursor.getColumnIndex("id");
                int foodNameIndex = cursor.getColumnIndex("food");
                int weightIndex = cursor.getColumnIndex("weight");
                int consumptionIndex = cursor.getColumnIndex("consumption");
                int dateIndex = cursor.getColumnIndex("date");
                int typeIndex = cursor.getColumnIndex("type");

                while (cursor.moveToNext()) {
                    int id = cursor.getInt(idIndex);
                    String foodName = cursor.getString(foodNameIndex);
                    int weight = cursor.getInt(weightIndex);
                    double consumption = cursor.getDouble(consumptionIndex);
                    String date = cursor.getString(dateIndex);
                    String type = cursor.getString(typeIndex);

                    dinnerItems.add(new Mealitem(id, foodName, weight, consumption, date, type));
                }
            } finally {
                cursor.close();  // 关闭游标
            }
        }
        return dinnerItems;
    }
}